import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import { GetStudentsQueryDto } from '../dto/get-students-query.dto';

@Injectable()
export class GetStudentsQueryParseIntPipe implements PipeTransform {
  // tslint:disable-next-line: ban-types
  constructor(private readonly metatypes: Function[]) {}

  transform(value: any, metadata: ArgumentMetadata): GetStudentsQueryDto {
    if (this.metatypes.includes(metadata.metatype)) {
      this.attributeValueParseInt(value, ['page', 'size']);
    }
    return value;
  }

  /**
   * 把一个对象里指定一些属性的值，转化为整数
   * @param o 对象
   * @param attributes 属性名数组
   */
  private attributeValueParseInt(o: any, attributes: string[]) {
    attributes.forEach(v => {
      if (undefined !== o[v]) {
        o[v] = parseInt(o[v], 10);
      }
    });
    return o;
  }
}
